package com.course.web.biz;

import com.course.domain.model.CourseInfo;
import com.course.domain.model.LearnStat;
import com.course.domain.model.Student;
import com.course.domain.service.CourseService;
import com.course.domain.service.LearnService;
import com.course.domain.service.UserService;
import com.course.util.DateUtils;
import com.course.web.model.LearnStatVM;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * Created by Justin on 2017/7/1.
 */
@Component
public class WebLearnBiz {

    private final CourseService courseService;
    private final LearnService learnService;
    private final UserService userService;

    @Autowired
    public WebLearnBiz(CourseService courseService,
                       LearnService learnService,
                       UserService userService) {
        this.courseService = courseService;
        this.learnService = learnService;
        this.userService = userService;
    }

    public List<LearnStatVM> findStat(int courseId, LocalDate today) {
        CourseInfo info = courseService.loadInfo(courseId);
        LocalDate begin = DateUtils.toLocalDate(info.getBeginDate());
        int weekIdx = DateUtils.calcWeekIdx(begin, today);
        int weekDay = DateUtils.calcWeekDay(begin, today);
        List<LearnStat> stats = learnService.findStat(courseId, weekIdx, weekDay);
        List<Integer> studentIds = Lists.transform(stats, LearnStat::getStudentId);
        List<Integer> courseIds = Lists.transform(stats, LearnStat::getCourseId);
        Map<Integer, Student> studentMap = Maps.uniqueIndex(userService.findStudent(studentIds), Student::getId);
        Map<Integer, CourseInfo> courseMap = Maps.uniqueIndex(courseService.findInfo(courseIds), CourseInfo::getId);
        return Lists.transform(stats, stat -> transform(stat, studentMap, courseMap));
    }

    private LearnStatVM transform(LearnStat stat, Map<Integer, Student> studentMap, Map<Integer, CourseInfo> courseMap) {
        LearnStatVM vm = new LearnStatVM();
        vm.setId(stat.getId());
        vm.setStudentId(stat.getStudentId());
        vm.setCourseId(stat.getCourseId());
        vm.setTotal(stat.getTotal());
        vm.setDone(stat.getDone());
        Student student = studentMap.get(stat.getStudentId());
        CourseInfo course = courseMap.get(stat.getCourseId());
        vm.setStudent(student != null ? student.getName() : "");
        vm.setCourse(course != null ? course.getTitle() : "");
        return vm;
    }
}
